package com.ease.oxm.jaxb;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class JaxbUtil {

	private static final String DEFAULT_ENCODING = "UTF-8";

	private static final transient Log log = LogFactory.getLog(JaxbUtil.class);

	public static String objectToXml(Object object) {
		if (null != object) {
			try {
				JAXBContext context = JAXBContext.newInstance(object.getClass());
				//
				Marshaller marshaller = context.createMarshaller();
				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
				marshaller.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_ENCODING);
				//
				StringWriter writer = new StringWriter();
				marshaller.marshal(object, writer);
				return writer.toString();
			} catch (Exception e) {
				log.error("objectToXml error object: " + object, e);
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T xmlToObject(String xml, Class<T> clazz) {
		if (null != xml) {
			try {
				JAXBContext context = JAXBContext.newInstance(clazz);
				Unmarshaller unmarshaller = context.createUnmarshaller();
				T object = (T) unmarshaller.unmarshal(new StringReader(xml));
				return object;
			} catch (Exception e) {
				log.error("xmlToObject error xml: " + xml, e);
			}
		}
		return null;
	}
}
